package com.wugui.datax.admin.controller;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.Hashtable;

public class LdapExample {

    public static void main(String[] args) {
        String ldapUrl = "ldap://114.217.149.21:389"; // LDAP 服务器地址
        String baseDn = "dc=hadoop,dc=com"; // 基本 DN
        String username = "cn=Manager,dc=hadoop,dc=com"; // LDAP 用户名
        String password = "bigdata@1q2w"; // LDAP 密码

        // 设置环境变量
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // 创建 LDAP 上下文
            DirContext ctx = new InitialDirContext(env);
            System.out.println("Connected to LDAP server.");

            // 搜索 LDAP 条目
            String searchFilter = "(objectClass=*)"; // 搜索所有条目
            NamingEnumeration<SearchResult> results = ctx.search(baseDn, searchFilter, null);

            while (results.hasMore()) {
                SearchResult result = results.next();
                System.out.println("Found entry: " + result.getNameInNamespace());
            }

           /* String newUserDn = "uid=newuser,ou=People," + baseDn;
            Attributes newUserAttributes = new BasicAttributes();
            newUserAttributes.put("objectClass", "inetOrgPerson");
            newUserAttributes.put("cn", "newuser");
            newUserAttributes.put("sn", "User");


            ctx.createSubcontext(newUserDn, newUserAttributes);
            System.out.println("Added new user: " + newUserDn);*/


/*
            // 添加条目
            String newUserDn = "uid=newuser,ou=People," + baseDn;
            Attributes newUserAttributes = new BasicAttributes();
            newUserAttributes.put("objectClass", "inetOrgPerson");
            newUserAttributes.put("cn", "newuser");
            newUserAttributes.put("sn", "User");

            ctx.createSubcontext(newUserDn, newUserAttributes);
            System.out.println("Added new user: " + newUserDn);

            // 修改条目
            ModificationItem[] mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute("mail", "updateduser@example.com"));
            ctx.modifyAttributes(newUserDn, mods);
            System.out.println("Updated user email for: " + newUserDn);

            // 删除条目
            ctx.destroySubcontext(newUserDn);
            System.out.println("Deleted user: " + newUserDn);
*/
            // 关闭上下文
            ctx.close();

        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}
